<?php

header( 'Content-Type: text/plain' );

set_time_limit( 0 );

if ( empty( $_GET['room'] ) || !trim( $_GET['room'] ) )
	$_GET['room'] = 'public';

$_GET['room'] = preg_replace( '/[^a-z0-9_\-]/', '', strtolower( trim( $_GET['room'] ) ) );

if ( !file_exists( dirname( __FILE__ ) . '/db/chat/' . $_GET['room'] . '.txt' ) )
	touch( dirname( __FILE__ ) . '/db/chat/' . $_GET['room'] . '.txt' );

if ( !(int)$_GET['pos'] || filesize( dirname( __FILE__ ) . '/db/chat/' . $_GET['room'] . '.txt' ) < (int)$_GET['pos'] ) {
	$_GET['pos'] = filesize( dirname( __FILE__ ) . '/db/chat/' . $_GET['room'] . '.txt' );
	$_GET['pos'] -= strlen( implode( '', array_slice( file( dirname( __FILE__ ) . '/db/chat/' . $_GET['room'] . '.txt' ), -25 ) ) );
}

$fp = fopen( dirname( __FILE__ ) . '/db/chat/' . $_GET['room'] . '.txt', 'r' );
fseek( $fp, $_GET['pos'] );

$i = filesize( dirname( __FILE__ ) . '/db/chat/' . $_GET['room'] . '.txt' ) == $_GET['pos'] ? 25000 : -1;
$size = filesize( dirname( __FILE__ ) . '/db/chat/' . $_GET['room'] . '.txt' );
while ( $i-- > 0 && filesize( dirname( __FILE__ ) . '/db/chat/' . $_GET['room'] . '.txt' ) == $size ) {
	clearstatcache();
	usleep( 10000 );
}

fpassthru( $fp );

echo "\n" . filesize( dirname( __FILE__ ) . '/db/chat/' . $_GET['room'] . '.txt' );

fclose( $fp );

?>